/**
 * Copyright (C) 2010, 2011 Neofonie GmbH
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package eu.dicodeproject.twitterstream.daemonize;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;

import eu.dicodeproject.twitterstream.StreamingBroker;

/**
 * Supports for easy daemonization of the twitter harvester tool. That includes being able to react
 * to regular system events for shutdown. Uses commons-daemon, and ultimately jsvc to accomplish
 * this task. That tool is distributed by Apache commons-daemon itself but is available on any major
 * Linux distribution natively as well.
 *
 * The implementation is not intended to be threadsafe. We expect there to run only one instance per JVM.
 */
public class TwitterDaemon {
  /** Logger for this class. */
  private static Logger LOG = LoggerFactory.getLogger(TwitterDaemon.class);
  /** Broker for tweets from twitter streaming to hbase.*/
  private StreamingBroker tweetBroker;

  private ConfigurableApplicationContext context = null;
  
  /**Initialize twitter broker - set up all objects needed for retrieving and storing tweets.
   */
  public void init() throws IOException {
    LOG.info("Initializing Twitter Broker daemon. Make sure to have started HBase before seeing this message.");
    this.context = new GenericXmlApplicationContext("eu.dicodeproject.twitterharvester.context.xml");
    this.tweetBroker = context.getBean(StreamingBroker.class);
    LOG.info("Service init done.");
  }

  /**Start twitter broker - retrieving messages via streaming and storing them in HBase.*/
  public void start() {
    LOG.info("Starting tweet broker.");
    this.tweetBroker.start();
    LOG.info("Service started.");
  }

  /** Stop storing tweets in HBase. */
  public void stop() {
    LOG.info("Stopping tweet broker.");
    this.context.stop();    
    LOG.info("Service stopped.");
  }

  /**Nothing really to be done here.*/
  public void destroy() {
    LOG.info("Stopping tweet broker.");
    this.context.stop();
    LOG.info("Service stopped.");
  }

  /** Getters here for testing purposes only - (ab-)use at your own risk for other things.*/
  StreamingBroker getTwitterBroker() {
    return this.tweetBroker;
  }

}
